import {
	loginByUsername,
	getUserInfo,
	logout,
	loginByPhone,refreshToken,addPartyGeoLocation
} from '@/api/login'

import {getStore,setStore, setState} from '@/common/util';

const user = {
	state: {
		forcedLogin: false,
		userId: getStore({
		  name: '$userId'
		})|| '',
		userInfo: getStore({
		  name: 'userInfo'
		}) || {},
		access_token: getStore({
		  name: 'access_token'
		}) || '',
		refresh_token: getStore({
		  name: 'refresh_token'
		}) || '',
		longitude: getStore({
		  name: '$longitude'
		}) || 0,
		latitude: getStore({
		name: '$latitude'
		}) || 0,
		hasLogin: getStore({
		name: '$has_login'
		}) || false,
		loginProvider: "",
		openid: null,
	},
	mutations: {
		SET_ACCESS_TOKEN: (state, access_token) => {
			state.access_token = access_token
		  setStore({
			name: 'access_token',
			content: state.access_token,
			type: 'session'
		  })
		},
		SET_LONGITUDE: (state, longitude) => {
			state.longitude = longitude;
			 setStore({
				name: '$longitude',
				content: state.longitude,
				type: 'session'
			})
		},
		SET_LATITUDE: (state, latitude) => {
			state.latitude = latitude;
			setStore({
				name: '$latitude',
				content: state.latitude,
				type: 'session'
			})
		},
		SET_USER_ID: (state, userId) => {
			state.userId = userId
			setStore({
			name: '$userId',
			content: state.userId,
			type: 'session'
			})
		},
		SET_USER_INFO: (state, userInfo) => {
		  state.userInfo = userInfo
//			console.log("userInfo")
		  setStore({
			name: 'userInfo',
			content: state.userInfo,
			type: 'session'
		  })
		},
		SET_REFRESH_TOKEN: (state, rfToken) => {
		  state.refresh_token = rfToken
		  setStore({
			name: 'refresh_token',
			content: state.refresh_token,
			type: 'session'
		  })
		},
		SET_HAS_LOGIN: (state, refIsLogin) => {
			state.hasLogin = refIsLogin
			setStore({
				name: '$has_login',
				content: state.hasLogin,
				type: 'session'
			})
		},
		UPDATE_USER_INFO: (state, data) =>  {
			const {
				key,
				value
			} = data;
			state.userInfo[key] = value;
			console.log("begin:" +JSON.stringify(state.userInfo));
			setStore({
				name: 'userInfo',
				content: state.userInfo,
				type: 'session'
			})
		},
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},

	},
	actions: {
		// lazy loading openid
		getUserOpenId: async function({
				commit,
				state
			}) {
				return await new Promise((resolve, reject) => {
					if (state.openid) {
						resolve(state.openid)
					} else {
						uni.login({
							success: (data) => {
								commit('login')
								setTimeout(function() { //模拟异步请求服务器获取 openid
									const openid = '123456789'
									console.log('uni.request mock openid[' + openid + ']');
									commit('setOpenid', openid)
									resolve(openid)
								}, 1000)
							},
							fail: (err) => {
								console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
								reject(err)
							}
						})
					}
				})
			},
			LoginByUsername({
				commit,
				state,
				dispatch
			}, userInfo) {
				commit('SET_ACCESS_TOKEN', '');
				commit('SET_REFRESH_TOKEN', '');
				var that = this;
				return new Promise((resolve, reject) => {
// 					const user = encryption({
// 						data: userInfo,
// 						key: '1234567887654321',
// 						param: ['password']
// 					})

					const user = userInfo;

					loginByUsername(user.username, user.password, user.code, user.randomStr).then(function(response) {
						console.log(JSON.stringify(response))
						const data = response
						setState(data.access_token)
						commit('SET_ACCESS_TOKEN', data.access_token);
						commit('SET_USER_ID', data.userId);
						commit('SET_REFRESH_TOKEN', data.refresh_token);
						commit('SET_HAS_LOGIN', true);
						//commit('CLEAR_LOCK');
						resolve();
					}).catch(error => {
						reject(error)
					})
				})
			},
			// 根据手机号登录
    LoginByPhone({
      commit,
      state,
      dispatch
    }, userInfo) {
      const mobile = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByPhone("mobile="+ mobile+"&code="+userInfo.code+"&grant_type=mobile&scope=server").then(function(response){
          const data = response
		  console.log(JSON.stringify(response))
		  if(response.status == -1) {
			  reject(response.message)
			  commit('SET_HAS_LOGIN', false);
		  } else {
			  setState(data.access_token)
			  commit('SET_ACCESS_TOKEN', data.access_token)
			  		commit('SET_USER_ID', data.userId);
			  commit('SET_REFRESH_TOKEN', data.refresh_token)
			  		commit('SET_HAS_LOGIN', true);
			  //commit('CLEAR_LOCK')
			  resolve()
		  }
          
        }).catch(error => {
          reject(JSON.stringify(error))
        })
      })
    },
	refreshTokenAction({commit,state, dispatch}) {
		console.log("hasLogin:"+state.hasLogin)
		if(state.hasLogin == true) {
			refreshToken(state.refresh_token).then(response => {
				
				console.log(JSON.stringify(response))
				
				setState(response.access_token)
				commit('SET_ACCESS_TOKEN', response.access_token)
				commit('SET_REFRESH_TOKEN', response.refresh_token)
			}).catch(err => {
				console.log("refresh token error:"+JSON.stringify(err));
			})
		}
		
	},
	 GetUserInfo({
      commit,
      state,
      dispatch
    }) {
     if(state.hasLogin == true) {
     	console.log(state.userId);
		
		 getUserInfo(state.userId).then(function(response) {
					console.log(JSON.stringify(response));
		 const data = response.data
		 //commit('SET_ROLES', data.roles)
		 commit('SET_USER_INFO', data)
					
		 //commit('SET_PERMISSIONS', data.permissions)
		 }).catch(error => {
			console.log(JSON.stringify(error))
		 })
	 }
    },
    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.access_token, state.refresh_token).then(() => {
//           // 清除菜单
//           commit('SET_MENU', [])
//           // 清除权限
//           commit('SET_PERMISSIONS', [])
          // 清除用户信息
					
          commit('SET_USER_INFO', {});
          commit('SET_ACCESS_TOKEN', '');
          commit('SET_USER_ID', '');
					commit('SET_REFRESH_TOKEN', '');
					commit('SET_HAS_LOGIN', false);
          // commit('SET_ROLES', [])
          //commit('DEL_ALL_TAG');
          
          setState("");
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 注销session
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
//         // 清除菜单
//         commit('SET_MENU', [])
//         // 清除权限
//         commit('SET_PERMISSIONS', [])
        // 清除用户信息
        commit('SET_USER_INFO', {});
        commit('SET_ACCESS_TOKEN', '');
        commit('SET_REFRESH_TOKEN', '');
		commit('SET_HAS_LOGIN', true);
        // commit('SET_ROLES', [])
        commit('DEL_ALL_TAG');
        removeState()
        resolve()
      })
    },
    // 注销session
    recordGeoPoint({
      commit,
      state,
      dispatch
      }, pointInfo) {
		
      return new Promise(resolve => {
		  
		  if(Math.abs(state.longitude - pointInfo.longitude) < 0.001 && Math.abs(state.latitude - pointInfo.latitude)  < 0.001) {
			  resolve();
			  return;
		  }
		  if(state.userId.length <= 0){
			  resolve();
		  }
		  else {
			  pointInfo.partyId = state.userId
			  pointInfo.createdBy = state.userId;
			  pointInfo.createdName = state.userInfo.userLoginId;
			  console.log(JSON.stringify(pointInfo))
				addPartyGeoLocation(pointInfo).then(response => {
					commit("SET_LONGITUDE", pointInfo.longitude)
					commit("SET_LATITUDE", pointInfo.latitude)
					resolve();
				}).catch(err => {
					console.error(err);
				})
		  }
		
      })
    },
	}
}

export default user
